package com.ww.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.PropertyMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.ldap.core.ContextSource;
import org.springframework.ldap.core.LdapOperations;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

@Slf4j
public class LdapTemplateUtil {

    private volatile static List<LdapTemplate> lts = new ArrayList<LdapTemplate>();
    static Object o = new Object();

    /**
     * 创建 LdapTemplate
     * @param username
     * @param pwd
     * @param base
     * @param urls
     * @return
     */
    public static LdapTemplate getLdapTemplate(String username, String pwd, String base, String... urls) {
        LdapContextSource source = new LdapContextSource();
        PropertyMapper propertyMapper = PropertyMapper.get().alwaysApplyingWhenNonNull();
        propertyMapper.from(username).to(source::setUserDn);
        propertyMapper.from(pwd).to(source::setPassword);
        propertyMapper.from(false).to(source::setAnonymousReadOnly);
        propertyMapper.from(base).to(source::setBase);
        propertyMapper.from(urls).to(source::setUrls);
        propertyMapper.from(new HashMap<String, String>()).to(
                (baseEnvironment) -> source.setBaseEnvironmentProperties(Collections.unmodifiableMap(baseEnvironment)));
        source.afterPropertiesSet();
        return new LdapTemplate(source);
    }

    /**
     * 获得模板集合
     * @return
     */
    public static List<LdapTemplate> get(){
        init();
        return lts;
    }

    /**
     * 初始化所有ldapTemplate
     */
    public static void init(){
        if (lts.isEmpty()){
            synchronized (o){
                if (lts.isEmpty()){
                    // init
                    log.info("templates cache cleared~");
                }
            }
        }


    }

    /**
     * 清除ldapTemplate缓存(新增ldap的时候可能需要)
     */
    public static void templatesCacheClear(){
        lts.clear();
        log.info("templates cache cleared~");
    }

}
